package com.banciyuan.bcywebview.utils.string;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Parcel;
import android.provider.Browser;
import android.text.TextPaint;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.regex.MyRegex;

import java.util.regex.Matcher;

/**
 * Created by squall on 2015/10/10.
 */
public class URLSpanNoUnderline extends URLSpan {

    private Context mContext;

    public URLSpanNoUnderline(String url) {
        super(url);
    }

    public URLSpanNoUnderline(Parcel src) {
        super(src);
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
        ds.setColor(mContext.getResources().getColor(R.color.timeline_green));
        ds.setUnderlineText(false);
    }

    @Override
    public void onClick(View widget) {
        try {
            Matcher matcher = MyRegex.plist.get(0).matcher(getURL());
            if (matcher.find()) {
                Uri uri = Uri.parse(getURL());
                Context context = widget.getContext();
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
                context.startActivity(intent);
            } else {
                goWeb();
            }
        } catch (Exception e) {
            goWeb();
        }
    }

    private void goWeb() {
        String url = "";
        if (getURL().contains("bcyapp_")) {
            url = getURL().substring(7);
        } else {
            url = getURL();
        }
        Intent intent = new Intent();
        intent.setClass(mContext, WebActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, url);
        mContext.startActivity(intent);
    }

    public void setContext(Context mContext) {
        this.mContext = mContext;
    }
}
